<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat App</title>
    <script src="js/vue.js"></script>
    <script src="element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    <script src="js/axios-0.18.0.js"></script>
    <style>
        #app {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-family: Arial, sans-serif;
        }
        .my-message {
            background-color: #DCF8C6;
            align-self: flex-end;
            margin-left: auto;
        }

        .other-message {
            background-color: #EAEAEA;
            align-self: flex-start;
            margin-right: auto;
        }

        .message-container {
            display: flex;
            flex-direction: column;
            gap: 10px;
            padding: 10px;
            max-height: 600px;
            overflow-y: auto;
        }

        .message-bubble {
            background-color: #FFFFFF;
            padding: 10px;
            border-radius: 10px;
            margin: 5px;
            word-wrap: break-word;
            max-width: 70%;
        }

        .message-sender {
            font-weight: bold;
            margin-bottom: 5px;
        }


    </style>
</head>
<body>
<div id="app">
    <!-- 用户ID输入框 -->
    <div>
<!--        <input type="text" v-model="userid" placeholder="输入您的用户名">-->
        <input type="text" v-model="title" placeholder="群聊" disabled>
<!--        <button @click="connectWebSocket">连接WebSocket</button>-->
    </div>

    <!-- 显示查看全部消息的按钮 -->
    <button v-if="showAllMessages" @click="showAllMessagesButton">查看全部消息</button>

    <div class="message-container">
        <div v-for="(msg, index) in messages2" :key="'messages2-' + index" :class="[msg.userid === userid ? 'my-message' : 'other-message']" style="display: flex">
            <p class="message-sender">{{ msg.userid }}</p>
            <p class="message-bubble">{{ msg.message }}</p>
        </div>
        <div v-for="(msg, index) in messages" :key="'messages-' + index" :class="[msg.sender.split('&:#')[0] === userid ? 'my-message' : 'other-message']" style="display: flex">
            <p class="message-sender">{{ msg.sender }}</p>
            <p class="message-bubble">{{ msg.message }}</p>
        </div>
    </div>



    <!-- 消息输入框 -->
    <div v-if="connected">
        <textarea
                rows="3"
                placeholder="输入您的消息"
                v-model="message"
                @keydown.enter.prevent="sendMessage"
                style="width: 100%;"
        ></textarea>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            userid: '',
            message: '',
            messages: [],
            messages2: [],
            ws: null,
            connected: false,
            title:'',
            showAllMessages: false ,// 控制是否显示全部消息

        },
        methods: {
            connectWebSocket() {
                if (!this.userid) {
                    alert("请输入您的用户名！");
                    return;
                }

                // 如果已经存在连接，先关闭它
                if (this.ws !== null && this.ws.readyState !== WebSocket.CLOSED) {
                    console.log("关闭现有的 WebSocket 连接。");
                    this.ws.close();
                }

                // 创建新的 WebSocket 连接，并在URL中包含用户ID
                this.ws = new WebSocket(`ws://localhost:9527/ws/${this.userid}/${this.title}`);

                this.ws.onopen = () => {
                    console.log(`WebSocket连接已打开! 用户ID: ${this.userid}+${this.title}`);
                    this.connected = true;
                };

                this.ws.onmessage = (event) => {
                    console.log("收到消息:", event.data);
                    const receivedData = event.data.split("&:#");
                    const sender = receivedData[0];
                    const message = receivedData[1];
                    const title = receivedData[2];
                    this.messages = this.messages.filter(message => {
                        return !(message.sender.includes('已经上线') || message.sender.includes('Connected users:') || message.sender.includes('left the chat.'));
                    });
                    this.messages.push({ sender: sender, message: message, title: title });
                };

                this.ws.onclose = () => {
                    console.log("WebSocket连接已关闭!");
                    this.connected = false;
                };
            },
            sendMessage() {
                if (this.message.trim() === '') {
                    alert("请输入消息内容！");
                    return;
                }

                const userid = this.userid.trim();
                if (!userid) {
                    alert("用户ID不能为空！");
                    return;
                }

                if (this.ws !== null && this.ws.readyState === WebSocket.OPEN) {
                    const messageToSend = `${userid}&:#${this.message}&:#${this.title}`; // 使用约定格式发送消息
                    this.ws.send(messageToSend);
                    axios.get("tools/makeSx",{params:{userid:this.userid,title:this.title,message:this.message}}).then(x=>{
                        if (x.data == 'ok'){
                            console.log('牛掰')
                        }
                    })
                    // this.messages.push({ sender: userid, message: this.message, title: this.title });
                    this.message = '';
                } else {
                    console.error("WebSocket连接未建立或已关闭。无法发送消息。");
                }
            },
            // 判断是否需要显示查看全部消息的按钮
            showAllMessagesButton() {
                axios.get("tools/getSx", {params: {title: this.title}}).then(x => {
                    this.messages2 = x.data;
                    this.showAllMessages = false;
                });

            }
        },
        mounted: function () {
            const queryString = window.location.search;
            const urlParams = new URLSearchParams(queryString);
            const useridValue = urlParams.get("userid");
            this.userid = useridValue.trim();
            const titleValue = urlParams.get("title");
            this.title = titleValue.trim();
            // 可以在mounted钩子中进行一些初始化操作
            axios.get("tools/getSx", {params: {title: this.title}}).then(x => {
                this.messages2 = x.data;
                if (this.messages2.length > 3){
                    this.showAllMessages = true;
                    this.messages2 = this.messages2.slice(-3); // 只显示前三条消息
                }
                this.connectWebSocket();
            })
        }
    });
</script>
</body>
</html>
